﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using AgingTest.Tools;

namespace AgingTest.DataProcess
{
    public enum TestState
    {
        free,       //0x06：空闲
        ready,      //0x07：马上开始测试 
        running,    //0x01：正在测试
        report,     //0x03：接收数据报告
        stop        //0x04：停止测试
    }
    public class TestData
    {

        public List<Dictionary<string, object>> PlatformList = new List<Dictionary<string, object>>();
        public bool WaitforSignal = false;
        public int PlatformNum { get; set; }
        public string MotorId { get; set; }
        public string CAN_ID { get; set; }
        public bool WaitForMsg { get; set; }
        public byte CurrentState { get; set; }
        public TestState Stage { get; set; }
        public byte[] SendData { get; set; }
        public int SendCount { get; set; }
        public int TimerSplit { get; set; }
        /////////////////////////////////////////////////////////////////////////////////////////////////////
        //接收报告buffer
        public byte[] ReportBuff = new byte[1024];
        public byte FinalProcesseByte = new byte();


        public PowerOnCheckStruct PowerOnCheck;
        //寻找电机零位
        public GetEleZeroStruct GetEleZero;
        //电动测试
        public PointMoveTestStruct PointMoveTest;
        //前置工况
        public PreconditionStruct Precondition;
        //外特性测试
        public ExteCharacterStruct ExteCharacter;
        //速度精度
        public SpeedAccuracyStruct SpeedAccuracy;
        //位置精度
        public PosAccuracyStruct PosAccuracy;
        //特定工况
        public SpecCondStruct SpecCond;


        public string ReportStr = "";

        public string ErrorInfo = "";
        public string FinalProcess = "";
        public byte ErrorCodeHex = 0x00;


        /// <summary>
        /// 构造函数初始化数据
        /// </summary>
        /// <param name="PlatformNum"></param>
        /// <param name="CAN_ID"></param>
        public TestData(int tempPlatformNum, string strCAN_ID)
        {
            PlatformNum = tempPlatformNum;
            CAN_ID = strCAN_ID;
            WaitForMsg = false;
            CurrentState = 0x06;
            Stage = TestState.free;
            SendData = null;
            SendCount = 0;
            TimerSplit = 0;

            ReportBuff.Initialize();

        }

        /// <summary>
        /// 构造函数初始化数据
        /// </summary>
        /// <param name="tempPlatformNum"></param>
        public TestData(int tempPlatformNum)
        {
            PlatformNum = tempPlatformNum;
            CAN_ID = "";
            WaitForMsg = false;
            CurrentState = 0x06;
            Stage = TestState.free;
            SendData = null;
            SendCount = 0;
            TimerSplit = 0;

            ReportBuff.Initialize();
        }


        public void IniPlatformAdd(int PlatformNum,string CAN_ID)
        {
            Dictionary<string, object> TestMap = new Dictionary<string, object>()
            {
                ["TestBedNum"] = PlatformNum,
                ["CAN_ID"] = CAN_ID,
                ["WaitForMsg"] = false,
                ["CurrentState"] = 0x06,            //下位机返回数据：0x01：正在测试，0x03：接收数据报告，0x06：空闲，0x07：马上开始测试 
                ["Stage"] = TestState.free,         //free：空闲，ready：启动中，running：运行中
                ["SendData"] = null,                //放置发送字符串
                ["SendCount"]=0,
                ["TimerSplit"]=0,
                              
            };
            PlatformList.Add(TestMap);
        }

        /// <summary>
        /// 序列化obj为byte[]
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] Serialize(object obj)
        {
            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            bf.Serialize(stream, obj);
            byte[] datas = stream.ToArray();
            stream.Dispose();
            return datas;
        }


        /// <summary>
        /// 最终的包解析函数
        /// </summary>
        /// <param name="data"></param>
        public  void AnalysisData(byte[] data)
        {

            //uint8_t finallyProcess;             //最终工序号

            //powerOnCheckStruct powerOnCheck;    //上电检测
            //getEleZeroStruct GetEleZero;        //寻找电机零位
            //pointMoveTestStruct pointMoveTest;  //点动测试
            //preconditionStruct precondition;    //前置工况
            //exteCharacterStruct exteCharacter;  //外特性测试
            //speedAccuracyStruct speedAccuracy;  //速度精度
            //posAccuracyStruct posAccuracy;      //位置精度
            //specCondStruct specCond;			  //特定工况

            byte finallyProcess = data[0];  //最终工序号
            FinalProcesseByte = data[0];
            byte ErrCode = 0x00;

            //上电检测
            PowerOnCheck = new PowerOnCheckStruct(data.Skip(1).Take(7).ToArray());
            //寻找电机零位
            GetEleZero = new GetEleZeroStruct(data.Skip(8).Take(2).ToArray());
            //电动测试
            PointMoveTest = new PointMoveTestStruct(data.Skip(10).Take(56).ToArray());
            //前置工况
            Precondition = new PreconditionStruct(data.Skip(66).Take(112).ToArray());
            //外特性测试
            ExteCharacter = new ExteCharacterStruct(data.Skip(178).Take(392).ToArray());
            //速度精度
            SpeedAccuracy = new SpeedAccuracyStruct(data.Skip(570).Take(332).ToArray());
            //位置精度
            PosAccuracy = new PosAccuracyStruct(data.Skip(902).Take(14).ToArray());
            //特定工况
            SpecCond = new SpecCondStruct(data.Skip(916).Take(2).ToArray());

            string FinallyProcessName = "";
            switch (finallyProcess)
            {
                case 0x00:
                    FinallyProcessName = "上电检测";
                    ErrCode = PowerOnCheck.errorCode;
                    break;
                case 0x01:
                    FinallyProcessName = "寻找电机零位";
                    ErrCode = GetEleZero.errorCode;
                    break;
                case 0x02:
                    FinallyProcessName = "点动测试";
                    ErrCode = PointMoveTest.errorCode;
                    break;
                case 0x03:
                    FinallyProcessName = "前置工况";
                    ErrCode = Precondition.errorCode;
                    break;
                case 0x04:
                    FinallyProcessName = "外特性测试";
                    ErrCode = ExteCharacter.errorCode;
                    break;
                case 0x05:
                    FinallyProcessName = "速度精度";
                    ErrCode = SpeedAccuracy.errorCode;
                    break;
                case 0x06:
                    FinallyProcessName = "位置精度";
                    ErrCode = PosAccuracy.errorCode;
                    break;
                case 0x07:
                    FinallyProcessName = "特定工况";
                    ErrCode = SpecCond.errorCode;
                    break;

                default:
                    break;
            }

            switch (ErrCode)
            {
                case 0xFD: ErrorInfo = "被测电机:脉冲驱动异常"; break;
                case 0x11: ErrorInfo = "被测电机:直流侧电流过大"; break;
                case 0x12: ErrorInfo = "被测电机:设定与实际速度差异过大"; break;
                case 0x13: ErrorInfo = "被测电机:扭矩差异过大"; break;
                case 0xFE: ErrorInfo = "测试过程中标准电机出现故障:"; break;

                case 0xA0: ErrorInfo = "被测电机:CAN回复超时"; break;
                case 0xA1: ErrorInfo = "被测电机:FOC超时"; break;
                case 0xA2: ErrorInfo = "被测电机:过压故障"; break;
                case 0xA3: ErrorInfo = "被测电机:欠压故障"; break;
                case 0xA4: ErrorInfo = "被测电机:过温故障"; break;
                case 0xA5: ErrorInfo = "被测电机:过流故障"; break;
                case 0xA6: ErrorInfo = "MC_SW_ERROR"; break;

                case 0xC0: ErrorInfo = "标准电机:CAN回复超时"; break;
                case 0xC1: ErrorInfo = "标准电机:FOC超时"; break;
                case 0xC2: ErrorInfo = "标准电机:过压故障"; break;
                case 0xC3: ErrorInfo = "标准电机:欠压故障"; break;
                case 0xC4: ErrorInfo = "标准电机:过温故障"; break;
                case 0xC5: ErrorInfo = "标准电机:过流故障"; break;
                case 0xC6: ErrorInfo = "MC_SW_ERROR";break;

                default:
                    if(ErrCode == 0)
                    {
                        ErrorInfo = "检测完毕，没有异常";
                    }
                    else
                    {
                        ErrorInfo = "出现未收录错误，故障码" + ErrCode.ToString("X2");
                    }

                    break;
            }

            if(finallyProcess == 0x07 && ErrCode == 0x00)
            {
                FinallyProcessName = "检测完毕，没有异常";
                ErrorInfo = "检测完毕，没有异常";
            }
            else
            {
                FinallyProcessName = "最终检测工序：" + FinallyProcessName + "。错误原因：" + ErrorInfo;
            }

            FinalProcess = FinallyProcessName;
            //string 
            Dictionary<string, object> ResultMap = new Dictionary<string, object>()
            {
                ["ProcessName"] = FinallyProcessName,
                ["PowerOnCheck"] = PowerOnCheck.ReportToStr(),
                ["GetEleZero"] = GetEleZero.ReportToStr(),
                ["PointMoveTest"] = PointMoveTest.ReportToStr(),
                ["Precondition"] = Precondition.ReportToStr(),
                ["ExteCharacter"] = ExteCharacter.ReportToStr(),
                ["SpeedAccuracy"] = SpeedAccuracy.ReportToStr(),
                ["PosAccuracy"] = PosAccuracy.ReportToStr(),
                ["SpecCond"] = SpecCond.ReportToStr(),
            };

            ReportStr = ResultMap["ProcessName"].ToString() + ResultMap["PowerOnCheck"]
                + ResultMap["GetEleZero"] + ResultMap["PointMoveTest"] + ResultMap["Precondition"]
                + ResultMap["ExteCharacter"] + ResultMap["SpeedAccuracy"] + ResultMap["PosAccuracy"]
                + ResultMap["SpecCond"] + "";

            ErrorCodeHex = ErrCode;

        }



        public void InsertSql()
        {
            Random ran = new Random();
            int RandKey = ran.Next(0, 1000);
            string TestId = DateTime.Now.ToString("yyyyMMddHHmmss_ms") + "_" + RandKey;
            string result = "";

            string sql = "";
            sql += "begin ";
            sql += PowerOnCheck.GetSql(MotorId, TestId);
            sql += GetEleZero.GetSql(MotorId, TestId);
            sql += PointMoveTest.GetSql(MotorId, TestId);
            sql += Precondition.GetSql(MotorId, TestId);
            sql += ExteCharacter.GetSql(MotorId, TestId);
            sql += SpeedAccuracy.GetSql(MotorId, TestId);
            sql += PosAccuracy.GetSql(MotorId, TestId);
            sql += SpecCond.GetSql(MotorId, TestId);
            if (ErrorCodeHex==0x00)
            {
                result = "1";
            }
            else
            {
                result = "0";
            }
            sql += "insert into t_d_TestMain (MotorId,TestId,ErrCode,ErrorInfo,TestTime,result,CANID,PlatformNum)" +
                " values ('"+MotorId+"','" + TestId + "','" + ErrorCodeHex.ToString("X2") + "','" + ErrorInfo + "','" + DateTime.Now.ToString() + "'," + result + "" +
                ",'"+CAN_ID+"','"+PlatformNum+"');";
            sql += " end";


            try
            {
                BaseDao.execute(sql);
            }
            catch (Exception e)
            {

                //throw;
            }
        }
    }


    /// <summary>
    /// 速度结构类
    /// </summary>
    public class SpeedStruct
    {
        public Int16 setSpeed;
        public Int16 getSpeed;

        //public SpeedStruct(byte[] data)
        //{
        //    setSpeed = BitConverter.ToInt16(data, 0);
        //    getSpeed = BitConverter.ToInt16(data, 2);
        //}

        public void IniSpeedStruct(byte[] data)
        {
            setSpeed = BitConverter.ToInt16(data, 0);
            getSpeed = BitConverter.ToInt16(data, 2);
        }

    }

    /// <summary>
    /// 转矩结构类
    /// </summary>
    public class TorqueStruct
    {
        public Int16 setTorque;
        public Int16 getTorque;


        //public TorqueStruct(byte[] data)
        //{
        //    setTorque = BitConverter.ToInt16(data, 0);
        //    getTorque = BitConverter.ToInt16(data, 2);
        //}

        public void IniTorqueStruct(byte[] data)
        {
            setTorque = BitConverter.ToInt16(data, 0);
            getTorque = BitConverter.ToInt16(data, 2);
        }

    }

    /// <summary>
    /// 位置测量结构类
    /// </summary>
    public class PositionStruct
    {
        public Int16 setPos;
        public Int16 getPos;

        //public PositionStruct(byte[] data)
        //{
        //    setPos = BitConverter.ToInt16(data, 0);
        //    getPos = BitConverter.ToInt16(data, 2);
        //}

        public void IniPositionStruct(byte[] data)
        {
            setPos = BitConverter.ToInt16(data, 0);
            getPos = BitConverter.ToInt16(data, 2);
        }


    }

    //   //上电检测结构体
    //   class powerOnCheckStruct
    //   {
    //       public:
    //       uint8_t process;        //工序号
    //       uint32_t timeRub;       //时间搓
    //       uint8_t eleCurrent;     //电流值
    //       uint8_t errorCode;      //错误码
    //   };

    /// <summary>
    /// 上电检测结构体类
    /// </summary>
    public class PowerOnCheckStruct
    {
        //1+4+1+1=7
        public byte process;        //工序号0
        public UInt32 timeRub;      //时间搓
        public byte eleCurrent;     //电流值
        public byte errorCode;      //错误码


        public PowerOnCheckStruct(byte[] data)
        {
            process = data[0];
            timeRub = BitConverter.ToUInt32(data,1);
            eleCurrent = data[5];
            errorCode = data[6];

        }

        public string GetSql(string MotorId,string TestId)
        {
            string sql = "";
            //sql = "insert into t_d_PowerONCheck (MotorId,TestId,TimeStamp,eleCurrent,ErrCode) VALUES (" +
            //    "'" + MotorId + "','" + TestId + "','"+timeRub.ToString()+"','"+ eleCurrent.ToString("D") + "'" +
            //    ",'"+ errorCode.ToString("X2") + "');";
            sql = BaseDao.GetSqlByInsert("t_d_PowerONCheck", new string[] { "MotorId", "TestId", "TimeStamp", "eleCurrent", "ErrCode" },
                new string[] { MotorId, TestId, timeRub.ToString(), (eleCurrent*5).ToString("D"), errorCode.ToString("X2") });
            return sql;
        }

        public string ReportToStr()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("");
            sb.AppendLine("工序名称：上电检测");
            sb.AppendLine("时间戳：" + timeRub.ToString() + ",电流值：" + (eleCurrent*5).ToString("D") + "mA" + ",错误码：" + errorCode.ToString("X2"));
            sb.AppendLine("");

            return sb.ToString();
        }

        public void Clear()
        {
            process = 0;
            timeRub = 0;
            eleCurrent = 0;
            errorCode = 0;
        }


    }



    //   //寻找电机零位结构体
    //   class getEleZeroStruct
    //   {
    //       public:
    //       uint8_t process;    //工序号
    //       uint8_t errorCode;  //错误码
    //   };

    /// <summary>
    /// 寻找电机零位结构类
    /// </summary>
    public class GetEleZeroStruct
    {
        //1+1=2
        public byte process;        //工序号1
        public byte errorCode;      //错误码

        public GetEleZeroStruct(byte[] data)
        {
            process = data[0];
            errorCode = data[1];
        }

        public string GetSql(string MotorId, string TestId)
        {
            string sql = "";
            sql = BaseDao.GetSqlByInsert("t_d_GetEleZero", new string[] { "MotorId", "TestId", "ErrCode" },
                new string[] { MotorId, TestId, errorCode.ToString("X2") });
            return sql;
        }

        public string ReportToStr()
        {
            StringBuilder sb = new StringBuilder();
            
            sb.AppendLine("工序名称：寻找电机零位");
            sb.AppendLine(",错误码：" + errorCode.ToString("X2"));
            sb.AppendLine("");

            return sb.ToString();
        }
    }

    //   //电动测试
    //   class pointMoveTestStruct
    //   {
    //       public:
    //       int8_t process;            //工序号
    //       uint32_t timeRub[6];        //时间搓
    //       speedStruct getSpeed[6];    //速度测量结构体
    //       uint8_t eleCurrent[6];      //电流值（单位mA）
    //       uint8_t errorCode;          //错误码
    //   };


    /// <summary>
    /// 点动测试结构类
    /// </summary>
    public class PointMoveTestStruct
    {
        //1+4*6+4*6+6+1=56
        public byte process;                                //工序号2
        public UInt32[] timeRub=new UInt32[6];              //时间搓
        public SpeedStruct[] getSpeed = new SpeedStruct[6]; //速度测量结构体
        public byte[] eleCurrent = new byte[6];             //电流值（单位mA）
        public byte errorCode;                              //错误码




        public PointMoveTestStruct(byte[] data)
        {
            process = data[0];
            for (int i = 0; i < 6; i++)
            {
                timeRub[i] = BitConverter.ToUInt32(data,1 + i * 4);
                getSpeed[i] = new SpeedStruct();
                getSpeed[i].IniSpeedStruct(data.Skip(1 + 4 * 6 + i * 4).Take(4).ToArray());
                eleCurrent[i] = data[1 + 4 * 6 + 4 * 6 + i];
            }
            errorCode = data[data.Length - 1];

        }

        public string GetSql(string MotorId, string TestId)
        {
            string sql = "";
            for (int i = 0; i < 6; i++)
            {
                sql += BaseDao.GetSqlByInsert("t_d_PointMoveTest", new string[] { "MotorId", "TestId","TimeStamp", "SetSpeed", "GetSpeed", "eleCurrent", "ErrCode" },
                    new string[] { MotorId, TestId,timeRub[i].ToString(),getSpeed[i].setSpeed.ToString("D"),getSpeed[i].getSpeed.ToString("D"), (eleCurrent[i]*5).ToString("D"), errorCode.ToString("X2") });
            }

            return sql;
        }

        public string ReportToStr()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("工序名称：寻找电机零位");
            for (int i = 0; i < 6; i++)
            {
                sb.AppendLine("时间戳：" + timeRub[i].ToString() + ",设定速度："+getSpeed[i].setSpeed.ToString("D")
                    +",实际速度："+getSpeed[i].getSpeed.ToString("D")+",电流值：" + (eleCurrent[i]*5).ToString("D") + "mA");
            }

            sb.AppendLine("错误码：" + errorCode.ToString("X2"));
            sb.AppendLine("");

            return sb.ToString();
        }


    }

    //   //前置工况测试结构体
    //   class preconditionStruct
    //   {
    //       public:
    //uint8_t process;            //工序号
    //       uint32_t timeRub[10];       //时间搓（ms）
    //       speedStruct getSpeed[10];   //速度测量
    //       uint8_t eleCurrent[10];     //电流值（mA）
    //       uint16_t temperature[10];   //温度值（℃）
    //       uint8_t errorCode;          //错误码
    //   };


    /// <summary>
    /// 前置工况测试结构类
    /// </summary>
    public class PreconditionStruct
    {
        //1+4*10+4*10+10+2*10+1
        public byte process;                                    //工序号3
        public UInt32[] timeRub = new UInt32[10];               //时间搓
        public SpeedStruct[] getSpeed = new SpeedStruct[10];    //速度测量
        public byte[] eleCurrent = new byte[10];                //电流值（mA）
        public UInt16[] temperature = new UInt16[10];           //温度值（℃）
        public byte errorCode;

        public PreconditionStruct(byte[] data)
        {
            process = data[0];
            for (int i = 0; i < 10; i++)
            {
                timeRub[i] = BitConverter.ToUInt32(data, 1 + i * 4);
                getSpeed[i] = new SpeedStruct();
                getSpeed[i].IniSpeedStruct(data.Skip(1 + 10 * 4 + i * 4).Take(4).ToArray());
                eleCurrent[i] = data[1 + 10 * 4 + 10 * 4 + i];
                temperature[i] = BitConverter.ToUInt16(data, 1 + 10 * 4 + 10 * 4 + 10 + i * 2);
            }
            errorCode = data[data.Length - 1];
        }

        public string GetSql(string MotorId, string TestId)
        {
            string sql = "";
            for (int i = 0; i < 10; i++)
            {
                sql += BaseDao.GetSqlByInsert("t_d_Precondition", new string[] { "MotorId", "TestId", "TimeStamp", "SetSpeed", "GetSpeed", "eleCurrent", "Temperature", "ErrCode" },
                    new string[] { MotorId, TestId, timeRub[i].ToString(), getSpeed[i].setSpeed.ToString("D"), getSpeed[i].getSpeed.ToString("D"), (eleCurrent[i]*5).ToString("D"), temperature[i].ToString("D"), errorCode.ToString("X2") });
            }

            return sql;
        }

        public string ReportToStr()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("工序名称：前置工况测试");
            for (int i = 0; i < 10; i++)
            {
                sb.AppendLine("时间戳：" + timeRub[i].ToString() + ",设定速度：" + getSpeed[i].setSpeed.ToString("D")
                    + ",实际速度：" + getSpeed[i].getSpeed.ToString("D") + ",电流值：" + (eleCurrent[i]*5).ToString("D") + "mA"
                    + ",温度："+temperature[i].ToString("D")+"°");
            }

            sb.AppendLine(",错误码：" + errorCode.ToString("X2"));
            sb.AppendLine("");

            return sb.ToString();
        }




    }


    //   //外特性测试结构体
    //   class exteCharacterStruct
    //   {
    //       public:
    //uint8_t process;                //工序号
    //       uint32_t timeRub[30];           //时间搓（ms）
    //       uint16_t eleStandardSpeed[30];  //标准电机转速（RPM）
    //       torqueStruct getTorque[30];     //转矩测量结构体
    //       uint8_t eleCurrent[30];         //电流值（mA）
    //       uint16_t tempearture[30];       //温度（℃）
    //       uint8_t errorCode;              //错误码
    //   };

    /// <summary>
    /// 外特性测试结构类
    /// </summary>
    public class ExteCharacterStruct
    {
        //1+4*30+2*30+4*30+1*30+2*30+1
        public byte process;                                    //工序号4
        public UInt32[] timeRub = new UInt32[30];               //时间搓
        public UInt16[] eleStandardSpeed = new UInt16[30];      //标准电机转速（RPM）
        public TorqueStruct[] getTorque = new TorqueStruct[30]; //转矩测量结构体
        public byte[] eleCurrent = new byte[30];                //电流值（mA）
        public UInt16[] temperature = new UInt16[30];           //温度值（℃）
        public byte errorCode;

        public ExteCharacterStruct(byte[] data)
        {
            process = data[0];
            for (int i = 0; i < 30; i++)
            {
                timeRub[i] = BitConverter.ToUInt32(data, 1 + i * 4);
                eleStandardSpeed[i] = BitConverter.ToUInt16(data, 1 + 30 * 4 + i * 2);
                getTorque[i] = new TorqueStruct();
                getTorque[i].IniTorqueStruct(data.Skip(1 + 30 * 4 + 30 * 2 + i * 4).Take(4).ToArray());
                eleCurrent[i] = data[1 + 30 * 4 + 30 * 2 + 30 * 4 + i];
                temperature[i] = BitConverter.ToUInt16(data, 1 + 30 * 4 + 30 * 2 + 30 * 4 + 30 + i * 2);
            }
            errorCode = data[data.Length - 1];

        }


        public string GetSql(string MotorId, string TestId)
        {
            string sql = "";
            for (int i = 0; i < 30; i++)
            {
                sql += BaseDao.GetSqlByInsert("t_d_ExteCharacter", new string[] { "MotorId", "TestId", "TimeStamp", "eleStandardSpeed", "SetTorque", "GetTorque", "eleCurrent", "Temperature", "ErrCode" },
                    new string[] { MotorId, TestId, timeRub[i].ToString(),eleStandardSpeed[i].ToString("D"), getTorque[i].setTorque.ToString("D"), getTorque[i].getTorque.ToString("D"), (eleCurrent[i]*5).ToString("D"), temperature[i].ToString("D"), errorCode.ToString("X2") });
            }

            return sql;
        }


        public string ReportToStr()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("工序名称：外特性测试");
            for (int i = 0; i < 30; i++)
            {
                sb.AppendLine("时间戳：" + timeRub[i].ToString() + ",标准电机转速：" + eleStandardSpeed[i].ToString("D")
                    + ",设定转矩：" + getTorque[i].setTorque.ToString("D") + ",实际转矩：" + getTorque[i].getTorque.ToString("D")+",电流值：" + (eleCurrent[i]*5).ToString("D") + "mA"
                    + ",温度：" + temperature[i].ToString("D") + "°");
            }

            sb.AppendLine(",错误码：" + errorCode.ToString("X2"));
            sb.AppendLine("");

            return sb.ToString();
        }

    }

    //   //速度精度测试结构体
    //   class speedAccuracyStruct
    //   {
    //       public:
    //uint8_t process;
    //       uint32_t timeRub[30];
    //       speedStruct getSpeed[30];
    //       int16_t eleTorque[30];      //被测电机转矩
    //       uint8_t eleCurrent[30];
    //       uint8_t errorCode;
    //   };


    /// <summary>
    /// 速度精度测试结构类
    /// </summary>
    public class SpeedAccuracyStruct
    {
        //1+4*30+4*30+2*30+30+1
        public byte process;                                    //工序号5
        public UInt32[] timeRub = new UInt32[30];               //时间搓
        public SpeedStruct[] getSpeed = new SpeedStruct[30];    //速度测量结构体
        public UInt16[] eleTorque = new UInt16[30];             //被测电机转矩
        public byte[] eleCurrent = new byte[30];                //电流值（mA）
        public byte errorCode;



        public SpeedAccuracyStruct(byte[] data)
        {
            process = data[0];
            for (int i = 0; i < 30; i++)
            {
                timeRub[i] = BitConverter.ToUInt32(data, 1 + i * 4);
                getSpeed[i] = new SpeedStruct();
                getSpeed[i].IniSpeedStruct(data.Skip(1 + 30 * 4 + i * 4).Take(4).ToArray());
                eleTorque[i] = BitConverter.ToUInt16(data, 1 + 30 * 4 + 30 * 4 + i * 2);
                eleCurrent[i] = data[1 + 30 * 4 + 30 * 4 + 30 * 2 + i];
            }
            errorCode = data[data.Length - 1];

        }


        public string GetSql(string MotorId, string TestId)
        {
            string sql = "";
            for (int i = 0; i < 30; i++)
            {
                sql += BaseDao.GetSqlByInsert("t_d_SpeedAccuracy", new string[] { "MotorId", "TestId", "TimeStamp", "SetSpeed", "GetSpeed", "eleTorque", "eleCurrent", "ErrCode" },
                    new string[] { MotorId, TestId, timeRub[i].ToString(), getSpeed[i].setSpeed.ToString("D"), getSpeed[i].getSpeed.ToString("D"), eleTorque[i].ToString("D"), (eleCurrent[i]*5).ToString("D"), errorCode.ToString("X2") });
            }

            return sql;
        }

        public string ReportToStr()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("工序名称：速度精度测");
            for (int i = 0; i < 30; i++)
            {
                sb.AppendLine("时间戳：" + timeRub[i].ToString() + ",设定速度：" + getSpeed[i].setSpeed.ToString("D")
                    + ",实际速度：" + getSpeed[i].getSpeed.ToString("D") + ",被测电机转矩：" + eleTorque[i].ToString("D") 
                    + ",电流值：" + (eleCurrent[i]*5).ToString("D") + "mA");
            }

            sb.AppendLine(",错误码：" + errorCode.ToString("X2"));
            sb.AppendLine("");

            return sb.ToString();
        }



    }


    //   //位置精度测试结构体
    //   class posAccuracyStruct
    //   {
    //       public:
    //       uint8_t process;
    //       uint32_t timeRub;
    //       PositionStruct posPosition; //正转位置测量
    //       PositionStruct negPosition; //反转位置测量
    //       uint8_t errorCode;
    //   };



    /// <summary>
    /// 位置精度测试结构类
    /// </summary>
    public class PosAccuracyStruct
    {
        //1+4+4+4+1
        public byte process;                                    //工序号6
        public UInt32 timeRub;               //时间搓
        public PositionStruct posPosition;                      //正转位置测量
        public PositionStruct negPosition;                      //反转位置测量
        public byte errorCode;


        public PosAccuracyStruct(byte[] data)
        {
            process = data[0];
            timeRub = BitConverter.ToUInt32(data, 1);

            posPosition = new PositionStruct();
            negPosition = new PositionStruct();

            posPosition.IniPositionStruct(data.Skip(1 + 1 * 4).Take(4).ToArray());
            negPosition.IniPositionStruct(data.Skip(1 + 1 * 4 + 4).Take(4).ToArray());
            errorCode = data[data.Length - 1];

        }


        public string GetSql(string MotorId, string TestId)
        {
            string sql = "";

            sql = BaseDao.GetSqlByInsert("t_d_PosAccuracy", new string[] { "MotorId", "TestId", "TimeStamp", "PosSetPos", "PosGetPos", "NegSetPos", "NegGetPos", "ErrCode" },
                new string[] { MotorId, TestId, timeRub.ToString(), posPosition.setPos.ToString("D"), posPosition.getPos.ToString("D"), negPosition.setPos.ToString("D"), negPosition.getPos.ToString("D"), errorCode.ToString("X2") });


            return sql;
        }


        public string ReportToStr()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("工序名称：位置精度测试");
            sb.AppendLine("时间戳：" + timeRub.ToString());
            sb.AppendLine("正转位置测量，" + "设定位置：" + posPosition.setPos.ToString("D") + ",实际位置：" + posPosition.getPos.ToString("D"));
            sb.AppendLine("反转位置测量，" + "设定位置：" + negPosition.setPos.ToString("D") + ",实际位置：" + negPosition.getPos.ToString("D"));
            //for (int i = 0; i < 1; i++)
            //{
            //    sb.AppendLine("时间戳：" + timeRub[i].ToString() + ",设定速度：" + getSpeed[i].setSpeed.ToString("D")
            //        + ",实际速度：" + getSpeed[i].getSpeed.ToString("D") + ",被测电机转矩：" + eleTorque[i].ToString("D")
            //        + ",电流值：" + eleCurrent[i].ToString("D") + "mA");
            //}

            sb.AppendLine(",错误码：" + errorCode.ToString("X2"));
            sb.AppendLine("");

            return sb.ToString();
        }

    }



    //   //特定工况测试结构体
    //   class specCondStruct
    //   {
    //       public:
    //uint8_t process;
    //       uint8_t errorCode;
    //   };

    public class SpecCondStruct
    {
        public byte process;                                    //工序号7
        public byte errorCode;

        public SpecCondStruct(byte[] data)
        {
            process = data[0];
            errorCode = data[1];

        }

        public string GetSql(string MotorId, string TestId)
        {
            string sql = "";

            sql = BaseDao.GetSqlByInsert("t_d_SpecCond", new string[] { "MotorId", "TestId", "ErrCode" },
                new string[] { MotorId, TestId,  errorCode.ToString("X2") });
            return sql;

        }


        public string ReportToStr()
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("工序名称：特定工况测试");
            sb.AppendLine(",错误码：" + errorCode.ToString("X2"));
            sb.AppendLine("");

            return sb.ToString();
        }

    }

}
